package com.example.q_kang.hhh.api;

import com.example.q_kang.hhh.login.LoginActivity;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.sskj.base.AppManager;
import com.sskj.base.base.App;
import com.sskj.base.base.HttpData;
import com.sskj.base.http.AbsConverter;
import com.sskj.base.http.JsonParseException;
import com.sskj.base.utils.GSonUtil;
import com.sskj.base.utils.ToastUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.lzy.okgo.callback.AbsCallback;
import okhttp3.ResponseBody;

/**
 * Created by lvzhihao on 17-7-4.
 */

public abstract class JsonConverter<T> extends AbsConverter<T> {

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        T data;
        try {
            String jsonBody = body.string();
            jsonBody = jsonBody.replace("\"data\":\"\"}", "\"data\":null}");
            Gson gson = GSonUtil.gson;
            Type genericSuperclass = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            data = gson.fromJson(jsonBody, type);
        } catch (Exception e) {
            throw new JsonParseException();
        }
        int status = 0;
        String msg = "";
        if (data instanceof HttpData) {
            status = ((HttpData) data).getStatus();
            msg = ((HttpData) data).getMsg();
        }

        if (status == 404) {
            ToastUtils.show(msg);
            HttpHeaders commonHeaders = OkGo.getInstance().getCommonHeaders();
            HttpParams commonParams = OkGo.getInstance().getCommonParams();
            commonHeaders.clear();
            commonParams.clear();
            commonHeaders.put("systemType", "ANDROID");
            commonParams.put("systemType", "ANDROID");
            OkGo.getInstance().addCommonHeaders(commonHeaders);
            OkGo.getInstance().addCommonParams(commonParams);
            AppManager.getInstance().finishAll();
            LoginActivity.start(App.INSTANCE);
//            LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
//            logoutProvider.logout();
        }
        //  根据状态码，统一处理（如用户过期，重新登录）
//        if (status == 100) {
//            ToastUtil.showShort(msg);
////            LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
////            logoutProvider.logout();
//        }
        return data;
    }

}
